package com.uenpay.util.xml;

import com.socks.library.KLog;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import java.io.IOException;
import java.io.StringReader;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * Sax解析无嵌套/无列表/键值对map  xml
 */
public class SaxParser {

	private static final String TAG = "SaxParser";

	public SaxParser() {

	}

	/**
	 * 解析无嵌套xml
	 * @param info xml内容
	 * @return Map<String, String> 键值对
	 * @throws SAXException
	 * @throws ParserConfigurationException
	 * @throws IOException
	 */
	public static Map<String, String> parser(String info) {

		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
	        SAXParser parser = factory.newSAXParser();
	        XMLReader reader = parser.getXMLReader();
	        SaxContentHandler handler = new SaxContentHandler();
	        reader.setContentHandler(handler);
	        reader.parse(new InputSource(new StringReader(info)));

	        // 解析得到键值对合集
	        Map<String, String> resultmap = handler.getMap();
			return resultmap;
		}
		catch (Exception e) {
			KLog.e(TAG, e.getMessage() + "报文解析异常");
        }
		return null;
	}

}
